package net.wofly.right.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alipay.api.internal.util.StringUtils;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinHelper;

import net.wofly.common.condition.Condition;
import net.wofly.common.condition.ConditionRelate;
import net.wofly.common.condition.ConditionUtil;
import net.wofly.common.condition.FilterCondition;
import net.wofly.common.condition.Operation;
import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.CommonStatus;
import net.wofly.common.util.CryptUserUtil;
import net.wofly.common.util.Identities;
import net.wofly.common.util.PageHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.right.domain.Organization;
import net.wofly.right.domain.RegisterVerifyInfo;
import net.wofly.right.domain.Role;
import net.wofly.right.domain.User;
import net.wofly.right.domain.UserReceivingAddr;
import net.wofly.right.domain.UserRegisterCheck;
import net.wofly.right.domain.UserRole;
import net.wofly.right.dto.MenuDto;
import net.wofly.right.dto.RightUserDto;
import net.wofly.right.repository.UserRepository;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IRegisterVerifyInfoService;
import net.wofly.right.service.IRightConfigService;
import net.wofly.right.service.IRoleService;
import net.wofly.right.service.IUserReceivingAddrService;
import net.wofly.right.service.IUserRegisterCheckService;
import net.wofly.right.service.IUserRoleService;
import net.wofly.right.service.IUserService;
import net.wofly.right.shiro.LoginType;
import net.wofly.right.shiro.MyUsernamePasswordToken;
import net.wofly.right.util.RegisterType;
import net.wofly.right.util.RegisterWay;
import net.wofly.right.util.RoleEnum;
import net.wofly.right.util.UserType;
import net.wofly.sale.stock.domain.Warehouse;
import net.wofly.sale.stock.service.IWarehouseService;
import net.wofly.sale.stock.util.WarehouseType;
import net.wofly.sms.SmsConfig;
import net.wofly.sms.SmsUtil;

@Service("iUserService")
@Transactional
public class UserServiceImpl implements IUserService {
    
    private static final Integer TWO_MINUTES = 2 * 60 * 1000;
    @Autowired
    UserRepository userRepository;
    @Autowired
    IUserRoleService iUserRoleService;
    @Autowired
    IRoleService iRoleService;
    @Autowired
    IRegisterVerifyInfoService iRegisterVerifyInfoService;
    @Autowired
    IUserRegisterCheckService iUserRegisterCheckService;
    @Autowired
    SmsConfig smsConfig;
    @Autowired
    IWarehouseService iWarehouseService;
    @Autowired
    IOrganizationService iOrganizationService;
    @Autowired
    IUserReceivingAddrService iUserReceivingAddrService;
    @Autowired
    IRightConfigService iRightConfigService;
    
    
    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    private String USER_DEF_PWD = "123456";
    
    @Override
    public User save(User entity) {
        try {
            if (!StringUtils.isEmpty(entity.getName())) {
                entity.setNamePinYin(PinyinHelper.getShortPinyin(entity.getName()));
            }
        } catch (PinyinException e) {
            e.printStackTrace();
        }
        return userRepository.save(entity);
    }
    
    @Override
    public void delete(User entity) {
        userRepository.delete(entity);
    }
    
    @Override
    public void delete(String key) {
        userRepository.delete(key);
    }
    
    @Override
    public User findOne(String key) {
        return userRepository.findOne(key);
    }
    
    @Override
    public List<User> findAll() {
        return (List<User>) userRepository.findAll();
    }
    
    @Override
    public Page<User> findAll(Specification specification, Pageable pageable) {
        return userRepository.findAll(specification, pageable);
    }
    
    @Override
    public List<User> save(List<User> entityList) {
        return (List<User>) userRepository.save(entityList);
    }
    
    @Override
    public List<User> findByMobile(String mobile) {
        return userRepository.findByMobile(mobile);
    }
    
    @Override
    public User findByMobileAndPassword(String mobile, String password) {
        User user = userRepository.findByMobileAndPassword(mobile, password);
        if (null != user && StringUtils.isEmpty(user.getName())) {
            user.setName(user.getMobile());
        }
        return user;
    }
    
    @Override
    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }
    
    @Override
    public List<User> findByOrganizationID(String organizationID) {
        return userRepository.findByOrganizationID(organizationID);
    }
    
    @Override
    public List<User> findByOrganizationIDAndStatus(String organizationID, Integer status) {
        return userRepository.findByOrganizationIDAndStatus(organizationID, status);
    }
    
    @Override
    public Page<User> findByOrganizationIDAndStatus(
            String organizationID, Integer status, Pageable pageable) {
        return userRepository.findByOrganizationIDAndStatus(organizationID, status, pageable);
    }
    
    @Override
    public List<User> findByNameLike(String name) {
        return userRepository.findByNameLike(name);
    }
    
    @Override
    public List<User> findByNamePinYinLike(String namePinYin) {
        return userRepository.findByNamePinYinLike(namePinYin);
    }
    
    @Override
    public List<User> findByNameContaining(String name) {
        return userRepository.findByNameContaining(name);
    }
    
    @Override
    public List<User> findByMobileOrEmail(String mobileOrEmail) {
        return userRepository.findByMobileOrEmail(mobileOrEmail, mobileOrEmail);
    }
    
    @Override
    public List<User> findByMobileOrEmail(String mobile, String email) {
        return userRepository.findByMobileOrEmail(mobile, email);
    }
    
    @Override
    public List<User> findByFollowUserID(String followUserID) {
        return userRepository.findByFollowUserID(followUserID);
    }
    
    @Override
    public List<User> findByFollowUserIDAndStatus(String followUserID, Integer status) {
        return userRepository.findByFollowUserIDAndStatus(followUserID, status);
    }
    
    @Override
    public List<User> findByFollowUserIDAndUserID(String followUserID, String userID) {
        return userRepository.findByFollowUserIDAndUserID(followUserID, userID);
    }
    
    @Override
    public List<User> findByFollowUserIDAndNameLike(String followUserID, String name) {
        return userRepository.findByFollowUserIDAndNameLike(followUserID, name);
    }
    
    @Override
    public List<User> findByFollowUserIDAndNamePinYinLike(String followUserID, String namePinYin) {
        return userRepository.findByFollowUserIDAndNamePinYinLike(followUserID, namePinYin);
    }
    
    /**
     * 添加一个客户
     * <ul>
     * <li>业务员或团购专员及店员、会计都可以添加一个客户</li>
     * <li>添加客户时，要判断当前添加客户是否存在</li>
     * <li>业务员添加的客户需要会计审核</li>
     * <li>判断当前用户是否有审核添加客户的权限，如果有则直接添加成功</li>
     * </ul>
     *
     * @param user
     */
    @Override
    public ReturnBean<String> addUser(User user) {
        List<User> us = findByMobile(user.getMobile());
        if (null != us && us.size()>0) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "添加失败，该客户（会员）已注册");
        }
        
        Role role = iRoleService.findOne(user.getRoleID());
        if (role == null) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "用户角色（roleID）不正确");
        }
        
        // 根据操作者权限设置用户是否需要审核 ， 代理注册的用户，可以知道其角色，通过角色判断
        String agencyId = user.getAgencyUserID();
        //user.setFollowUserID(user.getAgencyUserID());
        
        if (null == user.getUserID()) {
            user.setUserID(Identities.uuid2());
        }
        
        
        if (StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(this.USER_DEF_PWD);
        }
        user.setPassword(CryptUserUtil.generatePassword(user.getPassword()));
        user.setRegisterType(RegisterType.agencyRegister.getValue());
        user.setModifyDate(System.currentTimeMillis());
        
        //注释以下代码，在权限模块中校验
        /*List<UserRole> userRoles = iUserRoleService.findByUserID(agencyId);
        if (!CollectionUtils.isEmpty(userRoles)) {
            for (UserRole userRole : userRoles) {
                Role role = iRoleService.findOne(userRole.getRoleID());
                if (!(role.getRoleName().equals(RoleEnum.会计.getName())
                        || role.getRoleName().equals(RoleEnum.业务员.getName())
                        || role.getRoleName().equals(RoleEnum.店员.getName())
                        || role.getRoleName().equals(RoleEnum.团购专员.getName()))) {
                    return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "代理注册的员工的权限不足，不能添加会员");
                }
                if (role.getRoleName().equals(RoleEnum.会计.getName()))
                    user.setStatus(1);
                break;
            }
        } else {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "代理注册的员工的权限不足，不能添加会员");
        }*/
        
        
        if (user.getWarehouseFlag() == 1) {// 有仓库
            // 内部员工才有仓库, 内部员工分 销售和店员 销售对应的是销售仓库，店员对应的是店面的仓库, 从角色表中配置信息得到仓库类型
            if (role.getWarehouseFlag().intValue() == 1) {
                user.setWarehouseType(role.getWarehouseType());
                
                switch (role.getWarehouseType()) {
                    case 1:    //WarehouseType.公司总仓库.getValue() :
                        List<Warehouse> warehouseList = iWarehouseService.findByWarehouseTypeAndStatus(
                                WarehouseType.公司总仓库.getValue().toString(),
                                CommonStatus.有效.getValue());
                        if (!CollectionUtils.isEmpty(warehouseList)) {
                            user.setWarehouseID(warehouseList.get(0).getWarehouseID());
                        } else {
                            logger.info(">>>未找到公司总仓库信息");
                        }
                        break;
                    case 2:    //WarehouseType.部门仓库.getValue() :
                        user.setWarehouseID(user.getOrganizationID());
                        break;
                    case 3:    //WarehouseType.个人仓库.getValue():
                        //当时个人仓库是否存在，不存在则创建个人仓库
                        iWarehouseService.createPersonalWareHouse(user.getUserID(), user.getName());
                        user.setWarehouseID(user.getUserID());
                }
                
                /*if (role.getWarehouseType() == WarehouseType.公司总仓库.getValue()) {
                    List<Warehouse> warehouseList = iWarehouseService.findByWarehouseTypeAndStatus(
                            WarehouseType.公司总仓库.getValue().toString(),
                            CommonStatus.有效.getValue());
                    if (!CollectionUtils.isEmpty(warehouseList)) {
                        user.setWarehouseID(warehouseList.get(0).getWarehouseID());
                    } else {
                        logger.info(">>>未找到公司总仓库信息");
                    }
                }
                if (role.getWarehouseType() == WarehouseType.部门仓库.getValue()) {
                    user.setWarehouseID(user.getOrganizationID());
                }
                if (role.getWarehouseType() == WarehouseType.个人仓库.getValue()) {
                		//当时个人仓库是否存在，不存在则创建个人仓库
                		iWarehouseService.createPersonalWareHouse(user.getUserID(), user.getName()) ;
                    user.setWarehouseID(user.getUserID());
                }*/
            }
        }
        
        save(user);
        
        UserRole userRole = new UserRole();
        userRole.setUserRoleID(user.getUserID());
        userRole.setRoleID(user.getRoleID());
        userRole.setUserID(user.getUserID());
        userRole.setSetUserID(user.getOptUser());
        userRole.setModifyDate(user.getModifyDate());
        iUserRoleService.save(userRole);
        
        return new ReturnBean<String>(ResultCode.SUCCESS, "添加成功");
    }
    
    @Override
    public ReturnBean<String> checkUser(User user, String userID) {
        // 判断操作者是否有审核权限
        List<Role> roles = iUserRoleService.findRolesByUserID(userID);
        boolean flag = false;
        if (CollectionUtils.isEmpty(roles)) {
            for (Role role : roles) {
                if (role.getRoleName().equals(RoleEnum.会计.getName())) {
                    flag = true;
                    break;
                }
            }
        }
        if (!flag) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "权限不足，不能进行会员审核");
        }
        
        User dbCus = findOne(user.getUserID());
        if (null == dbCus) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "客户信息有误，客户（会员）不存在");
        }
        user.setModifyDate(System.currentTimeMillis());
        //状态有前端传过来
        save(user);
        
        UserRegisterCheck check = new UserRegisterCheck();
        check.setUserRegisterCheckID(Identities.uuid2());
        //  设置操作的雇员
        check.setCheckUserID(userID);
        check.setUserID(user.getUserID());
        check.setModifyDate(System.currentTimeMillis());
        iUserRegisterCheckService.save(check);
        
        return new ReturnBean<String>(ResultCode.SUCCESS, "审核成功");
    }
    
    @Override
    public ReturnBean<String> finishRegisterByMobile(String mobile, String password, String verifyCode) {
        
    		List<User> us = findByMobile(mobile);
        if (null != us && us.size()>0) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "手机号码已经注册，请登录");
        }
        
        //校验验证码
        List<RegisterVerifyInfo> registerVerifyInfos = iRegisterVerifyInfoService
                .findByRegisterAccountOrderByRegisterTimeDesc(mobile);
        if (CollectionUtils.isEmpty(registerVerifyInfos)) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "手机号不正确或者验证码失效");
        }
        
        RegisterVerifyInfo registerVerifyInfo = registerVerifyInfos.get(0);
        if (registerVerifyInfo.getInvalidTime() < System.currentTimeMillis()) {
            return new ReturnBean<String>(2, "验证码失效，请重新申请发送验证码");
        }
        
        if (!verifyCode.equals(registerVerifyInfo.getVerifyCode())) {
            return new ReturnBean<String>(2, "验证码错误");
        }
        
        User user = new User();
        user.setUserID(Identities.uuid2());
        user.setRegisterTime(System.currentTimeMillis());
        user.setModifyDate(System.currentTimeMillis());
        user.setRegisterWay(RegisterWay.手机号注册.getValue());
        user.setRegisterType(RegisterType.selfRegister.getValue());
        
        user.setMobile(mobile);
        user.setPassword(CryptUserUtil.generatePassword(password));
        user.setStatus(1);
        user.setUserType(UserType.个人客户.getValue());
        //会员默认为法人
        user.setIsLegal(1);
        //会员的组织机构默认设置为100200100，公众
        Organization org = iOrganizationService.findByOrganizationCode("100200100") ;
        if (null != org) {
	        	user.setOrganizationID(org.getOrganizationID());
        }
        
        save(user);
        
        UserRole userRole = new UserRole();
        userRole.setUserRoleID(Identities.uuid2());
        //会员
        userRole.setRoleID("201");
        userRole.setUserID(user.getUserID());
        iUserRoleService.save(userRole);
        
        return new ReturnBean<String>(ResultCode.SUCCESS, "注册成功");
    }
    
    @Override
    public ReturnBean<User> login(HttpServletRequest request, String accountID, String password) {
        try {
            MyUsernamePasswordToken token = new MyUsernamePasswordToken(accountID,
                    CryptUserUtil.generatePassword(password), LoginType.CUSTOMER);
            SecurityUtils.getSubject().login(token);
            User user = findByMobileAndPassword(accountID, CryptUserUtil.generatePassword(password));
            List<Role> roles = iUserRoleService.findRolesByUserID(user.getUserID());
            if (!CollectionUtils.isEmpty(roles)) {
                user.setRole(roles.get(0));
                
                List<MenuDto> menuDtos = iRightConfigService.getRightConfigByRoleIDForLogin(user.getRole().getRoleID());
                user.setMenus(menuDtos);
            }
            
            return new ReturnBean<User>(ResultCode.SUCCESS, "登录成功", user);
        } catch (Exception e) {
            return new ReturnBean<User>(ResultCode.ERROR_SERVICE, "登录失败，账号或密码不正确");
        }
    }

    @Override
    public ReturnBean<User> loginForMobile(HttpServletRequest request, String accountID, String password) {
        try {
            MyUsernamePasswordToken token = new MyUsernamePasswordToken(accountID,
                    CryptUserUtil.generatePassword(password), LoginType.CUSTOMER);
            SecurityUtils.getSubject().login(token);
            User user = findByMobileAndPassword(accountID, CryptUserUtil.generatePassword(password));
            List<Role> roles = iUserRoleService.findRolesByUserID(user.getUserID());
            if (!CollectionUtils.isEmpty(roles)) {
                Role role = roles.get(0);
                if (!checkUserRoleForLogin(role.getRoleID())) {
                    return new ReturnBean<>(ResultCode.ERROR_SERVICE, "您的角色是：" + role.getRoleName() + ",不能登录！");
                }
                user.setRole(role);

                List<MenuDto> menuDtos = iRightConfigService.getRightConfigByRoleIDForLogin(user.getRole().getRoleID());
                user.setMenus(menuDtos);
            }

            return new ReturnBean<>(ResultCode.SUCCESS, "登录成功", user);
        } catch (Exception e) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "登录失败，账号或密码不正确");
        }
    }

    private boolean checkUserRoleForLogin(String roleID){
        if (roleID.equals(RoleEnum.店员.getValue())) {
            return true;
        } else if (roleID.equals(RoleEnum.业务员.getValue())) {
            return true;
        } else if (roleID.equals(RoleEnum.会员客户.getValue())) {
            return true;
        } else if (roleID.equals(RoleEnum.团购客户.getValue())) {
            return true;
        } else if (roleID.equals(RoleEnum.流通客户.getValue())) {
            return true;
        } else if (roleID.equals(RoleEnum.酒店客户.getValue())) {
            return true;
        } else if (roleID.equals(RoleEnum.签单客户.getValue())) {
            return true;
        }
        return false;
    }
    
    @Override
    public ReturnBean<String> logout(String userID) {
        return null;
    }
    
    @Override
    public ReturnBean<String> sendMobileVerifyCode(String mobile) {
    		List<User> users = userRepository.findByMobile(mobile) ;
    		if (null == users || users.size()<=0) {
    			return new ReturnBean<String>(3, "您输入的手机号尚未注册！");
    		}
        
        //Q: 是否需要校验已经注册 ，或者在finish接口中校验  A: 在finish接口中校验
        
        //设置验证码获取的有效间隔，避免重复获取
        List<RegisterVerifyInfo> registerVerifyInfos = iRegisterVerifyInfoService
                .findByRegisterAccountOrderByRegisterTimeDesc(mobile);
        if (!CollectionUtils.isEmpty(registerVerifyInfos)) {
            RegisterVerifyInfo registerVerifyInfo = registerVerifyInfos.get(0);
            if (System.currentTimeMillis() < registerVerifyInfo.getRegisterTime() + TWO_MINUTES) {
                return new ReturnBean<String>(2, "请勿重复申请发送验证码");
            }
        }
        
        //调用三方短信平台，生成验证码
        String verifyCode = String.valueOf((int) (Math.random() * 9000 + 1000));
        
        StringBuffer msgText = new StringBuffer(smsConfig.getSignName());
        msgText.append("您的验证码是").append(verifyCode);
        SmsUtil.sendMsg(smsConfig.getApiKey(), mobile, msgText.toString());
        
        //将得到的验证码保存
        RegisterVerifyInfo registerVerifyInfo = new RegisterVerifyInfo();
        registerVerifyInfo.setRegisterVerifyInfoID(Identities.uuid2());
        registerVerifyInfo.setRegisterAccount(mobile);
        registerVerifyInfo.setVerifyCode(verifyCode);
        
        registerVerifyInfo.setRegisterTime(System.currentTimeMillis());
        registerVerifyInfo.setInvalidTime(System.currentTimeMillis() + TWO_MINUTES);
        
        iRegisterVerifyInfoService.save(registerVerifyInfo);
        
        //删除过期信息
        iRegisterVerifyInfoService.deleteByInvalidTimeLessThan(System.currentTimeMillis());
        
        return new ReturnBean<String>(ResultCode.SUCCESS, "获取验证码成功");
    }
    
    @Override
    public ReturnBean<String> sendMobileVerifyCodeForReg(String mobile) {
    		List<User> users = userRepository.findByMobile(mobile) ;
    		if (null != users && users.size()>0) {
    			return new ReturnBean<String>(3, "您要注册的手机号己存在，请重新输入手机号！");
    		}
        
        //Q: 是否需要校验已经注册 ，或者在finish接口中校验  A: 在finish接口中校验
        
        //设置验证码获取的有效间隔，避免重复获取
        List<RegisterVerifyInfo> registerVerifyInfos = iRegisterVerifyInfoService
                .findByRegisterAccountOrderByRegisterTimeDesc(mobile);
        if (!CollectionUtils.isEmpty(registerVerifyInfos)) {
            RegisterVerifyInfo registerVerifyInfo = registerVerifyInfos.get(0);
            if (System.currentTimeMillis() < registerVerifyInfo.getRegisterTime() + TWO_MINUTES) {
                return new ReturnBean<String>(2, "请勿重复申请发送验证码");
            }
        }
        
        //调用三方短信平台，生成验证码
        String verifyCode = String.valueOf((int) (Math.random() * 9000 + 1000));
        
        StringBuffer msgText = new StringBuffer(smsConfig.getSignName());
        msgText.append("您的验证码是").append(verifyCode);
        SmsUtil.sendMsg(smsConfig.getApiKey(), mobile, msgText.toString());
        
        //将得到的验证码保存
        RegisterVerifyInfo registerVerifyInfo = new RegisterVerifyInfo();
        registerVerifyInfo.setRegisterVerifyInfoID(Identities.uuid2());
        registerVerifyInfo.setRegisterAccount(mobile);
        registerVerifyInfo.setVerifyCode(verifyCode);
        
        registerVerifyInfo.setRegisterTime(System.currentTimeMillis());
        registerVerifyInfo.setInvalidTime(System.currentTimeMillis() + TWO_MINUTES);
        
        iRegisterVerifyInfoService.save(registerVerifyInfo);
        
        //删除过期信息
        iRegisterVerifyInfoService.deleteByInvalidTimeLessThan(System.currentTimeMillis());
        
        return new ReturnBean<String>(ResultCode.SUCCESS, "获取验证码成功");
    }
    
    @Override
    public ReturnBean<String> delUserFollow(String userFollowID) {
        return null;
    }
    
    @Override
    public ReturnBean<PageWrapper<User>> getAllUser(Integer status, Integer pageNum, Integer pageSize) {
        Condition condition = new Condition();
        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
        filterConditions.add(new FilterCondition(String.valueOf(status), "status", ConditionRelate.and.name(),
                Operation.eq.name(), 1));
        condition.setFilterCondition(filterConditions);
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), User.class).getResult();
        
        Pageable pageable = new PageRequest(pageNum - 1, pageSize);
        Page<User> page = findAll(condition.getSpecification(), pageable);
        
        
        return new ReturnBean<PageWrapper<User>>(ResultCode.SUCCESS, "查询成功", PageHelper.toPage(page));
    }
    
    @Override
    public ReturnBean<List<User>> getMyUserFollow(String userID) {
        User user = this.findOne(userID);
        if (user == null) {
            return new ReturnBean<List<User>>(ResultCode.ERROR_SERVICE, "userID不正确，员工不存在");
        }
        List<User> userList = findByFollowUserID(userID);
        
        Map<String, Organization> orgMap = iOrganizationService.getAllCampanyCustomerOrgMap();
        for (User u : userList) {
            u.setOrganization(orgMap.get(u.getOrganizationID()));
        }
        
        return new ReturnBean<List<User>>(ResultCode.SUCCESS, "查询成功", userList);
    }
    
    @Override
    public ReturnBean<String> setUserFollow(String employeeUserID, String customerUserID) {
        
        User customer = findOne(customerUserID);
        if (customer == null) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "客户不存在");
        }
        User employee = findOne(employeeUserID);
        if (employee == null) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "员工不存在");
        }
        
        customer.setFollowUserID(employeeUserID);
        customer.setModifyDate(System.currentTimeMillis());
        save(customer);
        
        return new ReturnBean<String>(ResultCode.SUCCESS, "设置成功");
    }
    
    @Override
    public ReturnBean<List<User>> getAllSales() {
        List<User> users = this.userRepository.findAllSales();
        return new ReturnBean<List<User>>(ResultCode.SUCCESS, "获取所有销售人员成功", users);
    }
    
    @Override
    public ReturnBean<String> addPersonalCustom(User user) {
        
        user.setIsLegal(1);
        user.setAgencyUserID(user.getOptUser());
        user.setFollowUserID(user.getOptUser());
        user.setOrganizationID("");
        user.setRegisterTime(System.currentTimeMillis());
        user.setModifyDate(System.currentTimeMillis());
        user.setRegisterType(2);
        user.setRegisterWay(1);
        user.setWarehouseFlag(0);
        
        return this.addUser(user);
    }
    
    @Override
    public ReturnBean<List<UserReceivingAddr>> getUserForOrder(String orderType, String saleUserID) {
        //TODO  判断用户类型确定用户
        
        List<UserReceivingAddr> userReceivingAddrs = iUserReceivingAddrService.getUserForOrder(orderType, saleUserID);
        
        return new ReturnBean<>(ResultCode.SUCCESS, "获取客户列表成功", userReceivingAddrs);
    }
    
    @Override
    public String findFollowUserByCustomer(String customUserID) {
        User user = this.userRepository.findOne(customUserID);
        if (null == user) {
            return "";
        }
        
        return user.getFollowUserID();
    }
    
    @Override
    public ReturnBean<List<User>> findShopUserByorganizationID(String organizationID) {
        List<User> users = this.userRepository.findByOrganizationID(organizationID);
        return new ReturnBean<>(ResultCode.SUCCESS, "获取组织机构下客户列表成功", users);
    }
    
    @Override
    public ReturnBean<PageWrapper<RightUserDto>> findAllUser(
            String name, String mobile, String roleID, String organizationID, Integer pageNum, Integer pageSize) {
        Integer startRow = (pageNum - 1) * pageSize;
        List<List<Object>> objects = userRepository.findAllUser(name, mobile, roleID, organizationID, startRow,
                pageSize);
        Long userCount = userRepository.countAllUser(name, mobile, roleID, organizationID);
        Long totalPages = userCount / pageSize;
        Long yuShu = userCount % pageSize;
        if (yuShu > 0) {
            totalPages++;
        }
        List<RightUserDto> rightUserList = new ArrayList<>(objects.size());
        for (Object obj : objects) {
            Object[] objArr = (Object[]) obj;
            RightUserDto rightUserDto = new RightUserDto();
            rightUserDto.setUserID(String.valueOf(objArr[0]));
//            rightUserDto.setUserName(String.valueOf(objArr[1]));
            rightUserDto.setMobile(String.valueOf(objArr[2]));
            rightUserDto.setName(String.valueOf(objArr[3]));
            if (objArr[4] != null) {
                Integer warehouseFlag = Integer.parseInt(String.valueOf(objArr[4]));
                rightUserDto.setWarehouseFlag(warehouseFlag);
                //是否有仓库标志 1:有；0:没有
                if (warehouseFlag == 1) {
                    rightUserDto.setWarehouseFlagStr("有");
                } else if (warehouseFlag == 0) {
                    rightUserDto.setWarehouseFlagStr("没有");
                }
            }
            if (objArr[5] != null) {
                Integer warehouseType = Integer.parseInt(String.valueOf(objArr[5]));
                rightUserDto.setWarehouseType(warehouseType);
                // 公司总仓库=1 ； 部门仓库=2 ；个人仓库=3
                if (warehouseType == 1) {
                    rightUserDto.setWarehouseTypeStr("公司总仓库");
                } else if (warehouseType == 2) {
                    rightUserDto.setWarehouseTypeStr("部门仓库");
                } else if (warehouseType == 3) {
                    rightUserDto.setWarehouseTypeStr("个人仓库");
                }
            }
            rightUserDto.setRoleName(String.valueOf(objArr[6]));
            rightUserDto.setOrganizationName(String.valueOf(objArr[7]));
            rightUserDto.setOrganizationID(String.valueOf(objArr[8]));
            rightUserDto.setRoleID(String.valueOf(objArr[9]));
            rightUserList.add(rightUserDto);
        }
        PageWrapper pageWrapper = new PageWrapper<>(pageNum - 1, pageSize, userCount, totalPages.intValue(),
                rightUserList);
        return new ReturnBean<>(ResultCode.SUCCESS, "获取所有公司内部用户成功!", pageWrapper);
    }
    
    @Override
    public ReturnBean<User> saveUserForUserManage(String userName, String mobile, String organizationID, String roleID) {
    	
    		List<User> us = userRepository.findByMobile(mobile) ;
    		if(null != us && us.size()>0) {
    			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "手机号己注册，请换个手机号重新注册！");
    		}
        
        //创建新用户
        User user = new User();
        user.setUserID(Identities.uuid2());
        if (StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(this.USER_DEF_PWD);
        }
        user.setPassword(CryptUserUtil.generatePassword(user.getPassword()));
        user.setName(userName);
        user.setUserName(userName);
        user.setMobile(mobile);
        user.setOrganizationID(organizationID);
        user.setRoleID(roleID);
        user.setUserType(0);
        
        user.setModifyDate(System.currentTimeMillis());
        
        Role role = iRoleService.findOne(roleID) ;
        if (null == role) {
        		return new ReturnBean<>(ResultCode.ERROR_SERVICE, "角色不存在！");
        }
        
        user.setWarehouseFlag(role.getWarehouseFlag());
        user.setWarehouseType(role.getWarehouseType());
        
        //设置用户角色
        UserRole userRole = new UserRole();
        userRole.setUserRoleID(Identities.uuid2());
        userRole.setUserID(user.getUserID());
        userRole.setRoleID(roleID);
        userRole.setModifyDate(user.getModifyDate());
        
        //根据用户角色中仓库类型，来为用户创建用户仓库或关联仓库
        Warehouse warehouse = null;
        if (role.getWarehouseFlag().equals(1)) {
        		if (role.getWarehouseType().equals(1)) {
        			warehouse = iWarehouseService.getCompanyWarehouse();
                if (null == warehouse) {
                		return new ReturnBean<>(ResultCode.ERROR_SERVICE, "当前用户配制为公司仓库，但公司仓库尚未创建，请创建公司仓库后再添加此用户！");
                }
                user.setWarehouseID(warehouse.getWarehouseID());
            }else if (role.getWarehouseType().equals(2)) {
                warehouse = iWarehouseService.getOrgWarehouse(user.getOrganizationID());
                if (null == warehouse) {
                		Organization org = iOrganizationService.findOne(user.getOrganizationID()) ;
                		return new ReturnBean<>(ResultCode.ERROR_SERVICE, "当前用户配制为"+ org.getOrganizationName() +"部门仓库，但仓库尚未创建，请创建仓库后再添加此用户！");
                }
                user.setWarehouseID(warehouse.getWarehouseID());
            } else if (role.getWarehouseType().equals(3)) {
                warehouse = iWarehouseService.createPersonalWareHouse(user.getUserID(), user.getUserName());
                if (null != warehouse) {
                    user.setWarehouseID(warehouse.getWarehouseID());
                }
            }
        }
        
        this.save(user);
        iUserRoleService.save(userRole);
        
        return new ReturnBean<>(ResultCode.SUCCESS, "创建用户成功！", user);
    }
    
    @Override
    public ReturnBean<User> updateUserForUserManage(String userID, String userName, String mobile, String organizationID, String roleID) {
        
        //修改用户
        User user = this.findOne(userID);
        
        if (null == user) {
            return new ReturnBean<>(ResultCode.ERROR_DATA, "要修改的用户不存在！id=" + userID);
        }
        
        List<User> us = userRepository.findByMobile(mobile) ;
		if(null != us) {
			for(User u:us) {
				if (user.getUserID() != u.getUserID()) {
					return new ReturnBean<>(ResultCode.ERROR_SERVICE, "您要修改的手机号己被注册，请换个手机号！");
				}
			}
		}
        
        user.setName(userName);
        user.setUserName(userName);
        user.setOrganizationID(organizationID);
        user.setRoleID(roleID);
        user.setModifyDate(System.currentTimeMillis());
        user.setUserType(0);
        
        Role role = iRoleService.findOne(roleID) ;
        if (null == role) {
        		return new ReturnBean<>(ResultCode.ERROR_SERVICE, "角色不存在！");
        }
        
        user.setWarehouseFlag(role.getWarehouseFlag());
        user.setWarehouseType(role.getWarehouseType());
        
        //设置用户角色
        List<UserRole> userRoles = iUserRoleService.findByUserID(userID);
        UserRole userRole;
        if (null != userRoles && !userRoles.isEmpty()) {
            userRole = userRoles.get(0);
            if (null != userRole) {
                userRole.setRoleID(roleID);
                iUserRoleService.save(userRole);
            }
        }
        
      //根据用户角色中仓库类型，来为用户创建用户仓库或关联仓库
        Warehouse warehouse = null;
        if (role.getWarehouseFlag().equals(1)) {
        		if (role.getWarehouseType().equals(1)) {
        			warehouse = iWarehouseService.getCompanyWarehouse();
                if (null == warehouse) {
                		return new ReturnBean<>(ResultCode.ERROR_SERVICE, "当前用户配制为公司仓库，但公司仓库尚未创建，请创建公司仓库后再添加此用户！");
                }
                user.setWarehouseID(warehouse.getWarehouseID());
            }else if (role.getWarehouseType().equals(2)) {
                warehouse = iWarehouseService.getOrgWarehouse(user.getOrganizationID());
                if (null == warehouse) {
                		Organization org = iOrganizationService.findOne(user.getOrganizationID()) ;
                		return new ReturnBean<>(ResultCode.ERROR_SERVICE, "当前用户配制为"+ org.getOrganizationName() +"部门仓库，但仓库尚未创建，请创建仓库后再添加此用户！");
                }
                user.setWarehouseID(warehouse.getWarehouseID());
            } else if (role.getWarehouseType().equals(3)) {
                warehouse = iWarehouseService.createPersonalWareHouse(user.getUserID(), user.getUserName());
                if (null != warehouse) {
                    user.setWarehouseID(warehouse.getWarehouseID());
                }
            }
        }
        
        this.save(user);
        
        return new ReturnBean<>(ResultCode.SUCCESS, "修改用户成功！", user);
    }
    
    @Override
    public ReturnBean<String> delUser(String userID) {
        User user = this.userRepository.findOne(userID);
        if (user == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户未找到！");
        }
        user.setStatus(0);
        this.userRepository.save(user);
        return new ReturnBean<>(ResultCode.SUCCESS, "禁用用户成功");
    }
    
    /**
     * 查询所有流通的和酒店的客户，在客户列表中搜索条件获取客户信息用
     * @return
     */
    @Override
    public ReturnBean<List<User>> getCustomerForCustomerSearch() {
        List<User> users = new ArrayList<>();
        //查 所有流通客户
        List<User> usersLt = iUserRoleService.findUsersByRoleID(RoleEnum.流通客户.getValue());
        //查询所有的酒店客户
        List<User> usersJd = iUserRoleService.findUsersByRoleID(RoleEnum.酒店客户.getValue());
        
        users.addAll(usersLt);
        users.addAll(usersJd);
    
        return new ReturnBean<>(ResultCode.SUCCESS, "查询成功", users);
    }
    
    /**
     * 修改用户手机号
     * @param userID
     * @param mobile
     * @return
     */
    @Override
    public ReturnBean<String> updateUserMobile(String userID,String mobile) {
    		//被修改用户
        User user = this.findOne(userID);
        if (null == user) {
            return new ReturnBean<>(ResultCode.ERROR_DATA, "要修改的用户不存在！id=" + userID);
        }
        
        List<User> us = this.findByMobile(mobile) ;
        if (null != us && us.size()>0) {
        		if (us.size()==1) {
        			if(user.getUserID().equals(us.get(0).getUserID())) {
            			return new ReturnBean<>(ResultCode.ERROR_DATA, "要修改的手机号就是当前用户手机号，无需修改。");
            		}
        		}
        		
            return new ReturnBean<>(ResultCode.ERROR_DATA, "当前手机号己被其他用户注册！请重复新输入其它未被注册的手机号。");
        }
        
        user.setMobile(mobile);
        user.setModifyDate(System.currentTimeMillis());
        this.save(user) ;
    		
        return new ReturnBean<>(ResultCode.SUCCESS, "当前用户手机号修改成功！");
    }
    
}
